/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.cheln.explorer.ds.scan;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import cn.cheln.explorer.beans.UpdateBean;
import cn.cheln.explorer.config.Config;
import cn.cheln.explorer.config.Constants;
import cn.cheln.explorer.ds.MediaArgs;
import cn.cheln.explorer.ds.util.ContentValuesUtil;

/**
 * 
 * @author Administrator
 */
public class MirrManager {
	public static final String[] LISTPROJECTION = new String[] {
			MediaArgs.PATH, MediaArgs.TITLE, MediaArgs.SIZE, MediaArgs.MODIFIED };

	public static final String[] COUNTPROJECTION = new String[] { MediaArgs.ID,
			MediaArgs.PATH, MediaArgs.SIZE, MediaArgs.MODIFIED, "sort_key" };
	public Map<String, MirrDetail> memoryImage = new HashMap<String, MirrDetail>();

	public Map<String, MirrDetail> getMemoryImage() {
		return memoryImage;
	}

	public MirrManager() {

		// if (Config.upperEqual_4_0) {
		memoryImage.put(Constants.CateContants.CATE_IMAGES, new MirrDetail(
				MediaArgs.ImageUri));
		memoryImage.put(Constants.CateContants.CATE_MUSIC, new MirrDetail(
				MediaArgs.AudioUri));
		memoryImage.put(Constants.CateContants.CATE_VIDEO, new MirrDetail(
				MediaArgs.VideoUri));
		// }
		memoryImage.put(Constants.CateContants.CATE_PACKAGE, new MirrDetail(
				MediaArgs.otherUri));
		memoryImage.put(Constants.CateContants.CATE_DOCS, new MirrDetail(
				MediaArgs.otherUri));
		memoryImage.put(Constants.CateContants.CATE_FOLDER, new MirrDetail(
				MediaArgs.dirUri));
		memoryImage.put(Constants.CateContants.CATE_THEME, new MirrDetail(
				MediaArgs.otherUri));
	}

	public void receiveDBImage(Context context, String categoryName) {
		if (categoryName == null
				|| categoryName.equals(Constants.CateContants.CATE_DOCS)) {
			String condition = (MediaArgs.MIMETYPE + " is not null" + " and ("
					+ MediaArgs.MIMETYPE + " not like '" + MediaArgs.APK_MIME
					+ "' and " + MediaArgs.MIMETYPE
					+ " like 'application%' ) or " + MediaArgs.MIMETYPE
					+ " like 'text%' and " + MediaArgs.FORMAT + " <> 12289");
			getContentInjected(
					queryOthersMirror(context, MediaArgs.otherUri, condition),
					memoryImage.get(Constants.CateContants.CATE_DOCS));
		}
		if (categoryName == null
				|| categoryName.equals(Constants.CateContants.CATE_PACKAGE)) {
			String condition = "format=12288 and lower(_data) like '%.apk' ";
			getContentInjected(
					queryOthersMirror(context, MediaArgs.otherUri, condition),
					memoryImage.get(Constants.CateContants.CATE_PACKAGE));
		}
		if (categoryName == null
				|| categoryName.equals(Constants.CateContants.CATE_FOLDER)) {
			String condition = "format=12289";
			getContentInjected(
					queryOthersMirror(context, MediaArgs.dirUri, condition),
					memoryImage.get(Constants.CateContants.CATE_FOLDER));
		}
		try {
			// if (Config.upperEqual_4_0) {
			if (categoryName == null
					|| categoryName.equals(Constants.CateContants.CATE_IMAGES)) {
				getContentInjected(
						lookForMediaFiles(context, MediaArgs.ImageUri, "image",
								"_data asc", COUNTPROJECTION),
						memoryImage.get(Constants.CateContants.CATE_IMAGES));
			}
			if (categoryName == null
					|| categoryName.equals(Constants.CateContants.CATE_MUSIC)) {
				getContentInjected(
						lookForMediaFiles(context, MediaArgs.AudioUri, "audio",
								"_data asc", COUNTPROJECTION),
						memoryImage.get(Constants.CateContants.CATE_MUSIC));
			}
			if (categoryName == null
					|| categoryName.equals(Constants.CateContants.CATE_VIDEO)) {
				getContentInjected(
						lookForMediaFiles(context, MediaArgs.VideoUri, "video",
								"_data asc", COUNTPROJECTION),
						memoryImage.get(Constants.CateContants.CATE_VIDEO));
			}
			// }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public synchronized Cursor queryOthersMirror(Context context, Uri otherUri,
			String condition) {

		return context.getContentResolver().query(otherUri, COUNTPROJECTION,
				condition, null, "_data asc");
	}

	public Cursor queryImage(Context context, Uri uri) {
		return context.getContentResolver()
				.query(uri, new String[] { MediaArgs.PATH, "_id" }, null, null,
						"_data asc");
	}

	public static synchronized Cursor lookForMediaFiles(Context context,
			Uri uri, String prefix_mime, String order,
			String... countProjection) {
		return context.getContentResolver().query(uri, countProjection,
				"mime_type like ? ",
				new String[] { prefix_mime.toLowerCase() + "%" }, order);
	}

	public static synchronized Cursor lookForImageMediaFiles(Context context,
			Uri uri, String prefix_mime, String order, String otherWhere,
			String... countProjection) {
		return context.getContentResolver().query(
				uri,
				countProjection != null ? countProjection : LISTPROJECTION,
				"mime_type like ? and _size > " + Config.image_filter_size
						* 1024, new String[] { prefix_mime + "%", }, order);
	}

	public Cursor queryFolderImage(Context context, Uri uri) {
		return context
				.getContentResolver()
				.query(uri,
						new String[] { MediaArgs.PATH
								+ ",_id,"
								+ MediaArgs.TITLE
								+ " from files where format=12289 order by _data asc --" },
						null, null, null);
	}

	public void getContentInjected(Cursor cursor, MirrDetail image) {
		String path = null;
		Integer id;
		String size;
		String lastM;
		String sort_key;
		UpdateBean ub;
		if (cursor == null) {
			return;
		}
		while (cursor.moveToNext()) {
			try {
				path = cursor.getString(cursor.getColumnIndex("_data"));
				id = cursor.getInt(cursor.getColumnIndex("_id"));
				sort_key = cursor.getString(cursor
						.getColumnIndex(MediaArgs.SORT_KEY));
				size = cursor.getString(cursor.getColumnIndex(MediaArgs.SIZE));
				lastM = cursor.getString(cursor
						.getColumnIndex(MediaArgs.MODIFIED));
				ub = new UpdateBean(id, path, size, lastM, sort_key,null);
				if (path == null || "".equals(path.trim())) {
					image.errorRecords.put(ub, path);
				} else {
					image.records.put(path, ub);
				}
			} catch (Exception e) {
				e.printStackTrace();

			}
		}
		cursor.close();
		cursor = null;
	}

	public static void delete(Context context, Uri uri, int data) {
		try {
			context.getContentResolver().delete(uri, "_id = ?",
					new String[] { data + "" });
		} catch (Exception e) {
		}
	}

	public void clearNoUseData(Context context) {
		for (MirrDetail image : memoryImage.values()) {
			for (UpdateBean ub : image.errorRecords.keySet()) {
				delete(context, image.operUri, ub.id);
			}
			for (UpdateBean ub : image.records.values()) {
				delete(context, image.operUri, ub.id);
			}
		}
	}

	public static boolean doDBSync(File file, Uri uri, Context context,
			boolean ifExists, UpdateBean ub, String ext) {

		return doDBSync(file, uri, context, ifExists,
				ub == null ? null : ub.id, ext);
	}

	public static boolean doDBSync(File file, Uri uri, Context context,
			boolean ifExists, Integer id, String ext) {
		if (ifExists) {

			return context.getContentResolver().update(uri,
					ContentValuesUtil.constructContentValues(file, ext),
					"_id = ?", new String[] { id + "" }) > 0;
		} else {
			return context.getContentResolver().insert(uri,
					ContentValuesUtil.constructContentValues(file, ext)) != null;
		}
	}
}
